import * as User from '../../api/users'

export const login = (payload, history) => async (dispatch) => {
  try {
    const { user } = await User.login(payload)
    localStorage.setItem('jwt', user.token)
    dispatch(setUser(user))
    dispatch(setErrList(null))
    history.replace('/')
  } catch (error) {
    dispatch(setErrList(error.response.data.errors))
  }
}

export const register = (payload, history) => async (dispatch) => {
  try {
    const { user } = await User.register(payload)
    localStorage.setItem('jwt', user.token)
    dispatch(setUser(user))
    dispatch(setErrList(null))
    history.replace('/')
  } catch (error) {
    dispatch(setErrList(error.response.data.errors))
  }
}

export const getUser = () => async (dispatch) => {
  try {
    const { user } = await User.user()
    dispatch(setUser(user))
  } catch (error) {
    console.log(error);
  }
}

export const updateUser = (history, payload) => async (dispatch) => {
  try {
    const { user } = await User.update(payload)
    dispatch(setUser(user))
    history.replace(`/@${user.username}`)
  } catch (error) {
    console.log(error);
  }
}

export const logout = (history) => (dispatch) => {
  dispatch(setUser(null))
  localStorage.removeItem('jwt')
  history.replace('/login')
}

export const setUser = user => ({
  type: 'setUser',
  user
})

export const setErrList = errors => ({
  type: 'setErrList',
  errors
})
